﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Easy.Model;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Easy.Common;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;
using Easy.DAL;

namespace Easy.Operation.Data
{
    public class PageForm
    {
        public string EntityName;
        public string EntityDispalayName;
        public string PreFix;
        public string ID;
        public Dictionary<string, Field> Fields;
        public Dictionary<string, object> EntityData;
        public Privilege UserPrivilege;
        public List<string> FunctionPrivilege;
        public Dictionary<string, List<OptionSet>> Options;
        private PageFormType Type = PageFormType.Create;
        private readonly SqlDatabase sqldb = new SqlDatabase(Config.TulingBuyCrmConnectString);
        public PageForm(HttpContext context, SystemUserModel user)
        {
            this.EntityName = context.Request["entityname"].ToLower();
            this.EntityDispalayName=GetDispalayName(this.EntityName);
            this.PreFix=GetPrefix().ToLower();
         
            this.ID = context.Request["id"];
            if (this.ID != null)
            {
                this.Type = PageFormType.Edit;
            }
            
            if (this.Type == PageFormType.Edit)
            {
                DataService service = new DataService(this.EntityName, user.SystemUserId);
                this.EntityData = service.Retrieve_Dic(new Guid(this.ID));
                //new PrivilegeDAL().IsHaveCreateRight(this.EntityName, user.SystemUserId, currentBusinessId, owningUserId, owningBusinessId)
            }

            Core core = new Core(EntityName);
            this.Fields = core.GetFields();
            this.Options = core.GetEntityOptions();
            this.UserPrivilege = core.GetPrivilege(user.SystemUserId);
            this.FunctionPrivilege = core.GetOprivilege(user.SystemUserId);
        }

       

        private string GetDispalayName(string entityname)
        {
            string sql = "select top 1 EntityDisplayName from EntityMap where EntityName = @entityname";
            SqlParameter[] param = new SqlParameter[] { 
                new SqlParameter("@entityname", entityname),
            };
            DbCommand cmd = sqldb.GetSqlStringCommand(sql);
            cmd.Parameters.AddRange(param);
            DataTable dt = sqldb.ExecuteDataSet(cmd).Tables[0];
            return sqldb.ExecuteDataSet(cmd).Tables[0].Rows[0][0].ToString();
        }
        private string GetPrefix()
        {
            string sql = "select top 1 Value from Parameter where Name = 'prefix'";
            DbCommand cmd = sqldb.GetSqlStringCommand(sql);
            DataTable dt = sqldb.ExecuteDataSet(cmd).Tables[0];
            return sqldb.ExecuteDataSet(cmd).Tables[0].Rows[0][0].ToString();
        }
        public List<string> GetFormStructure(string formname)
        {
            List<string> FormStructure = new List<string>();
            string sql = "SELECT TOP 1 [FormHtml],[FormButton],[FormJS_Src],[FormJS_beforeLoad],[FormJS_afterLoad],[FormJS_beforeSave],[FormJS_afterSave] FROM [Form] WHERE FormName = @formname AND EntityName = @entityname";
            SqlParameter[] param = new SqlParameter[] { 
                new SqlParameter("@entityname", this.EntityName),
                new SqlParameter("@formname", formname)
            };
            DbCommand cmd = sqldb.GetSqlStringCommand(sql);
            cmd.Parameters.AddRange(param);
            DataTable dt = sqldb.ExecuteDataSet(cmd).Tables[0];
            if (dt.Rows.Count > 0)
            {
                FormStructure.Add(sqldb.ExecuteDataSet(cmd).Tables[0].Rows[0]["FormHtml"].ToString());
                FormStructure.Add(sqldb.ExecuteDataSet(cmd).Tables[0].Rows[0]["FormButton"].ToString());
                FormStructure.Add(sqldb.ExecuteDataSet(cmd).Tables[0].Rows[0]["FormJS_Src"].ToString());
                FormStructure.Add(sqldb.ExecuteDataSet(cmd).Tables[0].Rows[0]["FormJS_beforeLoad"].ToString());
                FormStructure.Add(sqldb.ExecuteDataSet(cmd).Tables[0].Rows[0]["FormJS_afterLoad"].ToString());
                FormStructure.Add(sqldb.ExecuteDataSet(cmd).Tables[0].Rows[0]["FormJS_beforeSave"].ToString());
                FormStructure.Add(sqldb.ExecuteDataSet(cmd).Tables[0].Rows[0]["FormJS_afterSave"].ToString());
                return FormStructure;
            }
            else
            {
                return null;
            }
        }

        public DataTable GetAttachments()
        {
            if (this.ID != null)
            {
                string sql = string.Format(@"select * from Attachment where entityName=@EntityName and RecordId=@Id and DeletionStateCode = 0 order by CreatedOn asc");
                SqlParameter[] pams = new SqlParameter[]{
	            new SqlParameter("@EntityName",this.EntityName),
	            new SqlParameter("@ID",this.ID)
            };
                DbCommand cmd = sqldb.GetSqlStringCommand(sql);
                cmd.Parameters.AddRange(pams);
                DataTable dt = sqldb.ExecuteDataSet(cmd).Tables[0];


                return dt;
            }
            else
            {
                return null;
            }
        }
    }
    public enum PageFormType
    {
        Create, Edit
    }
}